package com.rpc.core.filter;

import com.rpc.core.holder.bean.Bean;
import com.rpc.core.holder.transmit.Request;
import com.rpc.core.holder.transmit.Response;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class InvokerChain {

    private List<RpcServiceFilter> list;

    private ConcurrentHashMap<String, Bean> exportMap;

    public void setExportMap(ConcurrentHashMap<String, Bean> exportMap) {
        this.exportMap = exportMap;
    }

    public InvokerChain(List<RpcServiceFilter> list) {
        this.list = list;
    }

    public Response invoke(Request request) {

        for (RpcServiceFilter filter : list) {
            Response response = filter.filter(request);
            if (response != null) {
                return response;
            }
        }

        String key = request.getKey();
        String[] strings = key.split("#");
        Bean bean = exportMap.get(strings[0]);
        if (bean == null) {
            throw new RuntimeException("The specified service could not be found!");
        }

        Object result = null;

        try {
            result = bean.invoke(strings[1], request.getArgs());
        } catch (Throwable e) {

            Response responseError = new Response();
            responseError.setId(request.getId());
            responseError.setInvokeSuccess(false);
            responseError.setThrowable(e);
            return responseError;
        }


        Response response = new Response();
        response.setId(request.getId());
        response.setInvokeSuccess(true);
        response.setResult(result);
        return response;
    }


}
